package com.xinqi.modules.user.users.user.manager.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.modules.user.user.domain.UserExtendEntity;
import com.xinqi.modules.user.user.dto.req.UserExtendQueryDTO;
import com.xinqi.common.mybatis.data.service.impl.BaseServiceImpl;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.user.users.user.manager.UserExtendManager;
import com.xinqi.modules.user.users.user.mapper.UserExtendMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * 用户扩展信息管理层实现
 *
 * @author: wenjie
 * @date: 2023/05/17
 */
@Service
@RequiredArgsConstructor
public class UserExtendManagerImpl extends BaseServiceImpl<UserExtendMapper, UserExtendEntity> implements UserExtendManager {

    /**
     * 根据id查询 用户扩展信息数据
     */
    @Override
    public UserExtendEntity findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return getById(id);
    }

    /**
     * 根据id删除 用户扩展信息数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return this.removeById(id);
    }

    /**
     * 通过用户ID删除
     *
     * @param userId
     * @return
     */
    @Override
    public void deleteByUserId(Long userId) {
        this.baseMapper.delete(new LambdaQueryWrapper<UserExtendEntity>().eq(UserExtendEntity::getUserId, userId));
    }

    @Override
    public UserExtendEntity findByUserId(Long userId) {
        UserExtendQueryDTO queryDTO = new UserExtendQueryDTO();
        queryDTO.setUserId(userId);
        return getOne(wrapper(queryDTO));
    }

    @Override
    public UserExtendEntity selectByIdCard(String idCard) {
        LambdaQueryWrapper<UserExtendEntity> wrapper = Queries.lambda();
        wrapper.eq(UserExtendEntity::getIdCard, idCard).last("LIMIT 1");
        return baseMapper.selectOne(wrapper);
    }

    private LambdaQueryWrapper<UserExtendEntity> wrapper(UserExtendQueryDTO query) {
        LambdaQueryWrapper<UserExtendEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(UserExtendEntity::getId, v));
        Queries.accept(query.getUserId(), v -> wrapper.eq(UserExtendEntity::getUserId, v));
        return wrapper;
    }

}
